import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class DataGenerator {
    private static final Random random = new Random();
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    
    // 相机型号选项
    private static final String[] CAMERA_MODELS = {
            "Canon EOS R5", "Sony A7R IV", "Nikon Z9", "Fujifilm X-T5",
            "Panasonic Lumix S5", "Sony A7 IV", "Canon EOS R6", "Nikon Z6 II"
    };
    
    // 时间段选项
    private static final String[] TIME_PERIODS = {"morning", "afternoon"};
    
    // 押金状态选项
    private static final String[] DEPOSIT_STATUSES = {"0", "1", "2"};
    
    // 人员姓名选项
    private static final String[] FIRST_NAMES = {
            "张", "李", "王", "刘", "陈", "杨", "赵", "黄", "周", "吴"
    };
    
    private static final String[] LAST_NAMES = {
            "伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "洋"
    };
    
    // 生成随机字符串ID
    private static String generateId(String prefix) {
        long timestamp = System.currentTimeMillis();
        String randomStr = String.format("%08d", random.nextInt(100000000));
        return prefix + "_" + timestamp + "_" + randomStr;
    }
    
    // 生成随机姓名
    private static String generateRandomName() {
        return FIRST_NAMES[random.nextInt(FIRST_NAMES.length)] +
                LAST_NAMES[random.nextInt(LAST_NAMES.length)];
    }
    
    // 生成随机日期（从2024年1月到2025年12月）
    private static String generateRandomDate() {
        // 随机选择年份（2024或2025）
        int year = 2024 + random.nextInt(2); // 2024或2025
        int month = random.nextInt(12) + 1; // 1-12月
        
        // 根据月份和年份确定天数
        int maxDay;
        switch (month) {
            case 2: // 2月
                if ((year == 2024) || (year == 2020) || (year == 2028)) { // 闰年判断
                    maxDay = 29;
                } else {
                    maxDay = 28;
                }
                break;
            case 4: case 6: case 9: case 11: // 小月
                maxDay = 30;
                break;
            default: // 大月
                maxDay = 31;
        }
        
        int day = random.nextInt(maxDay) + 1; // 1-maxDay日
        LocalDate date = LocalDate.of(year, month, day);
        return date.format(DATE_FORMATTER);
    }
    
    // 生成相机数据
    private static Camera generateCamera() {
        return new Camera(
                generateId("camera"),
                CAMERA_MODELS[random.nextInt(CAMERA_MODELS.length)],
                "SN" + (100000 + random.nextInt(900000)),
                LocalDateTime.now().format(TIMESTAMP_FORMATTER),
                LocalDateTime.now().format(TIMESTAMP_FORMATTER)
        );
    }
    
    // 生成订单数据
    private static Order generateOrder(String cameraModel, String cameraSerialNumber) {
        String pickupDate = generateRandomDate();
        LocalDate pickup = LocalDate.parse(pickupDate);
        LocalDate returnDate = pickup.plusDays(random.nextInt(5) + 1);
        
        return new Order(
                generateId("order"),
                cameraModel,
                cameraSerialNumber,
                generateRandomName(),
                generateRandomName(),
                generateRandomName(),
                pickupDate,
                TIME_PERIODS[random.nextInt(TIME_PERIODS.length)],
                returnDate.format(DATE_FORMATTER),
                TIME_PERIODS[random.nextInt(TIME_PERIODS.length)],
                DEPOSIT_STATUSES[random.nextInt(DEPOSIT_STATUSES.length)],
                "备注" + (random.nextInt(100)),
                LocalDateTime.now().format(TIMESTAMP_FORMATTER),
                LocalDateTime.now().format(TIMESTAMP_FORMATTER)
        );
    }
    
    // 生成完整数据
    public static void generateData(int count, String fileName) throws IOException {
        List<Camera> cameras = new ArrayList<>();
        List<Order> orders = new ArrayList<>();
        
        // 生成相机和订单数据
        for (int i = 0; i < count; i++) {
            Camera camera = generateCamera();
            cameras.add(camera);
            Order order = generateOrder(camera.getModel(), camera.getSerialNumber());
            orders.add(order);
        }
        
        // 创建数据容器
        DataContainer data = new DataContainer(cameras, orders,
                LocalDateTime.now().format(TIMESTAMP_FORMATTER), "1.0");
        
        // 写入JSON文件（使用UTF-8编码）
        try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(fileName), StandardCharsets.UTF_8)) {
            writer.write(data.toJson());
            System.out.println("数据已成功生成并保存到: " + fileName);
        }
    }
    
    public static void main(String[] args) {
        try {
            // 从命令行参数获取数据量，默认1000条
            int dataCount = 1000;
            if (args.length > 0) {
                try {
                    dataCount = Integer.parseInt(args[0]);
                } catch (NumberFormatException e) {
                    System.out.println("使用默认数据量: " + dataCount);
                }
            }
            
            String fileName = "相机租赁系统数据备份_2024-2025.json";
            generateData(dataCount, fileName);
        } catch (IOException e) {
            System.err.println("生成数据时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

// 相机数据模型
class Camera {
    private String id;
    private String model;
    private String serialNumber;
    private String createdAt;
    private String updatedAt;
    
    public Camera(String id, String model, String serialNumber, String createdAt, String updatedAt) {
        this.id = id;
        this.model = model;
        this.serialNumber = serialNumber;
        this.createdAt = createdAt;
        this.updatedAt = updatedAt;
    }
    
    // Getters and Setters
    public String getId() { return id; }
    public String getModel() { return model; }
    public String getSerialNumber() { return serialNumber; }
    public String getCreatedAt() { return createdAt; }
    public String getUpdatedAt() { return updatedAt; }
}

// 订单数据模型
class Order {
    private String id;
    private String cameraModel;
    private String cameraSerialNumber;
    private String renterName;
    private String customerService;
    private String salesperson;
    private String pickupDate;
    private String pickupTime;
    private String returnDate;
    private String returnTime;
    private String depositStatus;
    private String notes;
    private String createdAt;
    private String updatedAt;
    
    public Order(String id, String cameraModel, String cameraSerialNumber,
                 String renterName, String customerService, String salesperson,
                 String pickupDate, String pickupTime, String returnDate,
                 String returnTime, String depositStatus, String notes,
                 String createdAt, String updatedAt) {
        this.id = id;
        this.cameraModel = cameraModel;
        this.cameraSerialNumber = cameraSerialNumber;
        this.renterName = renterName;
        this.customerService = customerService;
        this.salesperson = salesperson;
        this.pickupDate = pickupDate;
        this.pickupTime = pickupTime;
        this.returnDate = returnDate;
        this.returnTime = returnTime;
        this.depositStatus = depositStatus;
        this.notes = notes;
        this.createdAt = createdAt;
        this.updatedAt = updatedAt;
    }
    
    // Getters and Setters
    public String getId() { return id; }
    public String getCameraModel() { return cameraModel; }
    public String getCameraSerialNumber() { return cameraSerialNumber; }
    public String getRenterName() { return renterName; }
    public String getCustomerService() { return customerService; }
    public String getSalesperson() { return salesperson; }
    public String getPickupDate() { return pickupDate; }
    public String getPickupTime() { return pickupTime; }
    public String getReturnDate() { return returnDate; }
    public String getReturnTime() { return returnTime; }
    public String getDepositStatus() { return depositStatus; }
    public String getNotes() { return notes; }
    public String getCreatedAt() { return createdAt; }
    public String getUpdatedAt() { return updatedAt; }
}

// 数据容器类
class DataContainer {
    private List<Camera> cameras;
    private List<Order> orders;
    private String exportDate;
    private String version;
    
    public DataContainer(List<Camera> cameras, List<Order> orders,
                         String exportDate, String version) {
        this.cameras = cameras;
        this.orders = orders;
        this.exportDate = exportDate;
        this.version = version;
    }
    
    // 转换为JSON字符串
    public String toJson() {
        StringBuilder json = new StringBuilder();
        json.append("{\n");
        json.append("  \"cameras\": [\n");
        
        // 添加相机数据
        for (int i = 0; i < cameras.size(); i++) {
            Camera cam = cameras.get(i);
            json.append("    {\n");
            json.append("      \"id\": \"").append(cam.getId()).append("\",\n");
            json.append("      \"model\": \"").append(cam.getModel()).append("\",\n");
            json.append("      \"serialNumber\": \"").append(cam.getSerialNumber()).append("\",\n");
            json.append("      \"createdAt\": \"").append(cam.getCreatedAt()).append("\",\n");
            json.append("      \"updatedAt\": \"").append(cam.getUpdatedAt()).append("\"\n");
            json.append("    }");
            if (i < cameras.size() - 1) json.append(",");
            json.append("\n");
        }
        
        json.append("  ],\n");
        json.append("  \"orders\": [\n");
        
        // 添加订单数据
        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            json.append("    {\n");
            json.append("      \"id\": \"").append(order.getId()).append("\",\n");
            json.append("      \"cameraModel\": \"").append(order.getCameraModel()).append("\",\n");
            json.append("      \"cameraSerialNumber\": \"").append(order.getCameraSerialNumber()).append("\",\n");
            json.append("      \"renterName\": \"").append(order.getRenterName()).append("\",\n");
            json.append("      \"customerService\": \"").append(order.getCustomerService()).append("\",\n");
            json.append("      \"salesperson\": \"").append(order.getSalesperson()).append("\",\n");
            json.append("      \"pickupDate\": \"").append(order.getPickupDate()).append("\",\n");
            json.append("      \"pickupTime\": \"").append(order.getPickupTime()).append("\",\n");
            json.append("      \"returnDate\": \"").append(order.getReturnDate()).append("\",\n");
            json.append("      \"returnTime\": \"").append(order.getReturnTime()).append("\",\n");
            json.append("      \"depositStatus\": \"").append(order.getDepositStatus()).append("\",\n");
            json.append("      \"notes\": \"").append(order.getNotes()).append("\",\n");
            json.append("      \"createdAt\": \"").append(order.getCreatedAt()).append("\",\n");
            json.append("      \"updatedAt\": \"").append(order.getUpdatedAt()).append("\"\n");
            json.append("    }");
            if (i < orders.size() - 1) json.append(",");
            json.append("\n");
        }
        
        json.append("  ],\n");
        json.append("  \"exportDate\": \"").append(exportDate).append("\",\n");
        json.append("  \"version\": \"").append(version).append("\"\n");
        json.append("}");
        return json.toString();
    }
}